#include <iostream>
#include <time.h>
#include "protocol.hpp"
#include "sock.hpp"


static void Usage(std::string proc)
{
    std::cout << "\n\t Usage" << proc << "./tcpcliet.exe ip port\n" << std::endl;
}

std::string opstr = "+-*/%";

int main(int argc, char* argv[])
{
    srand(time(nullptr));
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    sockfd.Connect(server_ip, server_port);

    int cnt = 0;
    while(cnt <= 10)
    {

        int data1 = rand() % 100;
        int data2 = rand() & 100;
        char op = opstr[rand() % opstr.size()];

        Request reqt(data1, op, data2);
        std::string package;
        reqt.serialize(package);
        package = Encode(package);

        std::cout << "=========第" << cnt << "任务========" << std::endl;
        reqt.Print();


        write(sockfd.GetSockfd(), package.c_str(), package.size());
        //write(sockfd.GetSockfd(), package.c_str(), package.size());

        
        char inbuffer[128];
        int n = read(sockfd.GetSockfd(), inbuffer, sizeof(inbuffer));
        if(n > 0)
        {   
            inbuffer[n] = '\0';
            Respone resp;
            std::string package(inbuffer);
            std::string content;
            Decode(package, content);
            resp.deserialize(content);
            resp.Print();
            std::cout << "=======================================\n" << std::endl;
        }

        sleep(1);
        cnt++;
    }

    sockfd.Close();


    return 0;
}